package com.codinghero.example.daily;

import java.util.Date;

public class VolatileExam2 {
	
	private static BackgroundFloobleLoader floobleLoader = new BackgroundFloobleLoader();
	
	public static void main(String[] args) {
		new Thread(floobleLoader).start();
		new Thread(new SomeOtherClass()).start();
		new Thread(new SomeOtherClass()).start();
		new Thread(new SomeOtherClass()).start();
	}
	
	public static class Flooble {
		
		public long data;
		
		public Flooble() {
			data = 0;
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			data = System.currentTimeMillis();
		}
	}

	public static class BackgroundFloobleLoader implements Runnable {
	    public Flooble theFlooble;

	    public void run() {
	        // do lots of stuff
			while (true) {
	    		theFlooble = new Flooble();  // this is the only write to theFlooble
//				try {
//					Thread.sleep(3000);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
	    	}
	    }
	}
	
	public static class SomeOtherClass implements Runnable {
		
	    public void run() {
	        while (true) { 
	            // do some stuff...
	            // use the Flooble, but only if it is ready
	            if (floobleLoader.theFlooble != null) {
					if (floobleLoader.theFlooble.data == 0)
						System.out.println("second=" + floobleLoader.theFlooble.data);
	            }
//	            try {
//					Thread.sleep(100);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
	        }
	    }
	}
}
